package main

import (
	"fmt"
	"io"
	"os"
	"time"
	
	"github.com/gin-contrib/zap"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

// 极致的性能
var logger *zap.Logger

func main() {
	initLogger()
	
	r := gin.New()
	r.Use(ginzap.Ginzap(logger, time.RFC3339, true))
	r.Use(ginzap.RecoveryWithZap(logger, true))
	
	r.GET("/ping", func(c *gin.Context) {
		c.String(200, "pong "+fmt.Sprint(time.Now().Unix()))
	})
	
	r.Run(":8080")
}

func initLogger() {
	// 编码方式
	encoder := getEncoder()
	// 输出位置
	writeSyncer := getLogWriter()
	core := zapcore.NewCore(encoder, writeSyncer, zap.DebugLevel)
	
	logger = zap.New(core, zap.AddCaller())
	
}

func getLogWriter() zapcore.WriteSyncer {
	// _ = os.MkdirAll("./customize-logger/data.log", os.ModePerm)
	file, _ := os.OpenFile("./data_test/test.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
	ws := io.MultiWriter(file, os.Stdout)
	return zapcore.AddSync(ws)
}

func getEncoder() zapcore.Encoder {
	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
	encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
	return zapcore.NewJSONEncoder(encoderConfig)
}
